package com.caine.tool;

import okhttp3.*;

import javax.net.ssl.*;
import java.io.IOException;

public class HttpTool {

    static OkHttpClient client = okHttpClientgetUnsafeOkHttpClient();

    public static String post(String url, String json) throws Exception {
        RequestBody body = RequestBody.create(MediaType.parse("json/application"),json);
        Request request = new Request.Builder().url(url).post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    /**

     * okHttp3添加信任所有证书

     * @return

     */

    public static OkHttpClient okHttpClientgetUnsafeOkHttpClient() {

        try {

            final TrustManager[] trustAllCerts = new TrustManager[]{

                    new X509TrustManager() {

                        @Override

                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {

                        }

                        @Override

                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {

                        }

                        @Override

                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {

                            return new java.security.cert.X509Certificate[]{};

                        }

                    }

            };

            final SSLContext sslContext = SSLContext.getInstance("TLS");

            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();

            //builder.sslSocketFactory(sslSocketFactory ）方法已过时，使用下面方法替代

            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);

            builder.hostnameVerifier(new HostnameVerifier() {

// 可以将不需要忽略的域名放入数组，也可为空（忽略所有证书）

                String[] arr = new String[]{};

                @Override

                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }

            });

            return builder.build();

        } catch (Exception e) {

            throw new RuntimeException(e);

        }
    }


    public static void main(String[] args) throws Exception {
        String json = "{\"data\":[]}";
        String post = post("http://pol4s-admin-1003720-func-2-pol4s.inapps.jqpqa.c.saic-gm.net/pol4sAdmin/rest/pol4s/orderParam/autoSubmit", json);
        System.out.println("post = " + post);
        
    }

}
